package com.lotusfall.mysport;

import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.MapsInitializer;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.maps.model.Text;
import com.lotusfall.mysport.controller.TrackController;
import com.lotusfall.mysport.entity.Weather;

import org.json.JSONException;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class FragmentRunning extends Fragment implements LocationSource,AMapLocationListener{
    TrackController trackController = new TrackController();
    List<LatLng> points = new ArrayList<LatLng>();
    String cityCode;
    MapView mMapView;
    AMap aMap;
    Button start;
    Button stop;
    CardView card_running;
    TextView timerView;
    TextView textDist;
    TextView text_city;
    TextView text_wea;
    TextView text_wind;
    TextView text_tem;
    ImageView wea_img;
    AMapLocationClient mLocationClient;
    AMapLocationClientOption mLocationOption;
    LocationSource.OnLocationChangedListener mListener;


    float dist = 0;
    LatLng pre;
    private long baseTimer; //上一次操作时间
    private Timer mTimer;
    boolean isOnRunning = false;
    public int count = 0;

    Polyline polyline;
    public FragmentRunning() {

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_running, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {

        super.onViewCreated(view, savedInstanceState);

        mMapView = (MapView)view.findViewById(R.id.map);//获取地图控件引用
        start = (Button) view.findViewById(R.id.startRuning);
        stop = (Button) view.findViewById(R.id.stopRuning);
        card_running = (CardView)view.findViewById(R.id.card_runnning);
        textDist = (TextView)view.findViewById(R.id.textDist);
        MapsInitializer.updatePrivacyShow(view.getContext(),true,true);
        MapsInitializer.updatePrivacyAgree(view.getContext(),true);
        mMapView.onCreate(savedInstanceState);//创建地图

        text_tem = (TextView)view.findViewById(R.id.tem);
        text_city = (TextView)view.findViewById(R.id.my_city);
        text_wea = (TextView)view.findViewById(R.id.wea);
        text_wind = (TextView)view.findViewById(R.id.wind);
        wea_img = (ImageView)view.findViewById(R.id.weather_img);

        // 开始跑步点击事件
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isOnRunning = true;
                start.setVisibility(View.INVISIBLE);
                card_running.setVisibility(View.VISIBLE);
                aMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_FOLLOW);
                aMap.animateCamera(CameraUpdateFactory.zoomTo(50));
                initTime();
                dist = 0;
            }
        });

        // 结束跑步点击事件
        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isOnRunning = false;
                card_running.setVisibility(View.INVISIBLE);
                aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
                start.setVisibility(View.VISIBLE);
                trackController.saveTrack(points,dist,view);
                points.removeAll(points);
                count = 0;
                dist = 0;
                aMap.clear();
                init();
            }
        });

        // 初始化地图控制器对象
        if (aMap == null) {
            aMap = mMapView.getMap();
        }
        init();
        // 获取城市编码用于获取天气
        Weather weather = new Weather();
        try {
            if(weather.getWeather(cityCode)){
                Log.e("weather:",weather.city);
                Log.e("weather:",weather.tem);
                text_wind.setText(weather.win_speed);
                text_wea.setText(weather.wea);
                text_city.setText(weather.city);
                text_tem.setText(weather.tem);

                switch (weather.wea_img){
                    case "yun":
                        wea_img.setImageResource(R.drawable.yun);
                        break;
                    case "yu":
                        wea_img.setImageResource(R.drawable.yu);
                        break;
                    case "yin":
                        wea_img.setImageResource(R.drawable.yin);
                        break;
                    case "qing":
                        wea_img.setImageResource(R.drawable.qing);
                        break;
                    case "xue":
                        wea_img.setImageResource(R.drawable.xue);
                        break;
                    case "lei":
                        wea_img.setImageResource(R.drawable.lei);
                        break;
                    case "shachen":
                        wea_img.setImageResource(R.drawable.shachen);
                        break;
                    case "wu":
                        wea_img.setImageResource(R.drawable.wu);
                        break;
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        // 初始化摄像头高度
        aMap.animateCamera(CameraUpdateFactory.zoomTo(17));
    }



    void initTime(){
        baseTimer = SystemClock.elapsedRealtime();
         timerView = (TextView)getView().findViewById(R.id.timerView);
         final Handler startTimehandler = new Handler(){
         public void handleMessage(android.os.Message msg) {
                if (null != timerView) {
                     timerView.setText((String) msg.obj);
                 }
             }
         };
         new Timer("开机计时器").scheduleAtFixedRate(new TimerTask() {
             @Override
             public void run() {
                 int time = (int)((SystemClock.elapsedRealtime() - baseTimer) / 1000);
                 String hh = new DecimalFormat("00").format(time / 3600);
                 String mm = new DecimalFormat("00").format(time % 3600 / 60);
                 String ss = new DecimalFormat("00").format(time % 60);
                String timeFormat = new String(hh + ":" + mm + ":" + ss);
                 Message msg = new Message();
                 msg.obj = timeFormat;
                 startTimehandler.sendMessage(msg);
             }

         }, 0, 1000L);
    }

    void init(){
        if (aMap == null) {
            aMap = mMapView.getMap();
        }
        //设置amap的一些属性
        UiSettings uiSettings = aMap.getUiSettings();
        uiSettings.setCompassEnabled(true);// 设置指南针是否显示
        uiSettings.setZoomControlsEnabled(true);// 设置缩放按钮是否显示
        uiSettings.setScaleControlsEnabled(true);// 设置比例尺是否显示
        uiSettings.setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示

        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER);//连续定位、蓝点不会移动到地图中心点，定位点依照设备方向旋转，并且蓝点会跟随设备移动。
        aMap.setMyLocationStyle(myLocationStyle);
        aMap.setLocationSource(this);// 设置定位监听
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        // 设置定位的类型为定位模式 ，可以由定位 LOCATION_TYPE_LOCATE、跟随 LOCATION_TYPE_MAP_FOLLOW 或地图根据面向方向旋转 LOCATION_TYPE_MAP_ROTATE
        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
        //使用 aMap.setMapTextZIndex(2) 可以将地图底图文字设置在添加的覆盖物之上
        aMap.setMapTextZIndex(2);
    }

    /**
     * 定位成功后回调函数
     */
    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (mListener != null && amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
                cityCode = amapLocation.getAdCode();
                System.out.println(cityCode);
                if(isOnRunning){
                    if(count>1){
                        float distance = AMapUtils.calculateLineDistance(points.get(count - 2), points.get(count - 1));
                        dist += distance;
                        textDist.setText(String.format("%.2f", dist) + "m");
                    }
                    Log.e("Amap", "location:" + amapLocation.getLatitude() + "," + amapLocation.getLongitude() + isOnRunning + "\n" + points);
                    LatLng newLatLng =  new LatLng(amapLocation.getLatitude(),amapLocation.getLongitude());
                    points.add(count, newLatLng);
                    count++;
                    drawLines();
                }

            } else {
                String errText = "定位失败," + amapLocation.getErrorCode()+ ": " + amapLocation.getErrorInfo();
                Log.e("AmapErr", errText);
                Toast.makeText(mMapView.getContext(), errText, Toast.LENGTH_SHORT).show();
            }
        }
    }
    /**
     * 绘制路线
     */
    public void drawLines() {
        PolylineOptions options = new PolylineOptions();
        //options.setCustomTexture(BitmapDescriptorFactory.fromResource(R.drawable.running));
        options.geodesic(true).setDottedLine(false).color(Color.GREEN).addAll(points).useGradient(true).width(10).visible(true);
        polyline = aMap.addPolyline(options);

        // 获取轨迹坐标点
        LatLngBounds.Builder b= LatLngBounds.builder();
        for (int i = 0; i< points.size(); i++) {
            b.include(points.get(i));
        }
        LatLngBounds bounds= b.build();

        //CameraUpdate update = CameraUpdateFactory.newLatLngBounds(bounds, 100);//
        //aMap.animateCamera(update);

    }

    /**
     * 激活定位
     */
    @Override
    public void activate(LocationSource.OnLocationChangedListener listener) {
        mListener = listener;
        if (mLocationClient == null) {
            try {
                mLocationClient = new AMapLocationClient(mMapView.getContext());
            } catch (Exception e) {
                e.printStackTrace();
            }
            mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mLocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mLocationClient.setLocationOption(mLocationOption);
            mLocationOption.setOnceLocation(false);
            mLocationOption.setGpsFirst(true);
            // 设置发送定位请求的时间间隔,最小值为1000ms,1秒更新一次定位信息
            mLocationOption.setInterval(10000);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mLocationOption.setMockEnable(true);
            mLocationClient.startLocation();
        }
    }

    @Override
    public void deactivate() {

    }
}

